package com.jason.concurrent.CountDownLatch;

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @Author  yslai
 * @Date  2022/9/19 17:28
 * @Description 创建信号灯方法
 */
public class SemaphoreDemo {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);

        for (int i = 0; i < 6; i++) {
            new Thread(()->{
                //抢占锁
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+"抢到了车位");

                    //需要离开车位
                    TimeUnit.SECONDS.sleep(new Random().nextInt(5));
                    System.out.println("离开了车位"+Thread.currentThread().getName());

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    //释放锁
                    semaphore.release();
                }
            },String.valueOf(i)).start();

        }
    }
}
